package com.shop.servlet;

import com.shop.service.IRegisterService;
import com.shop.service.RegisterService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    IRegisterService iregisterService = new RegisterService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        // 1. 获取请求参数
        String studentId = req.getParameter("username");
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        System.out.println("RegisterServlet:25:"+studentId+" "+phone+" "+password);
        // 2. 调用service方法
        boolean result = iregisterService.register(studentId, phone, password);
        // 3. 判断结果
        if (result) {
            // 注册成功
            System.out.println("RegisterServlet:31:注册成功");
            req.setAttribute("msg", "注册成功");
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {// 注册失败
            System.out.println("RegisterServlet:35:注册失败");
            req.setAttribute("msg", "账号或手机号已存在");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("register.jsp");
    }
}
